package net.omnivention.proxy;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import org.apache.log4j.Logger;

public class IOUtility {
	static final int BLOCK_SIZE = 101;

	private static Logger logger = Logger.getLogger(IOUtility.class);

	static final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();

	public static String readLine(InputStream is) throws IOException {

		StringBuffer line = new StringBuffer();
		int i;
		char c = 0x00;
		i = is.read();
		if (i == -1)
			return null;
		while (i > -1 && i != 10 && i != 13) {
			// Convert the int to a char
			c = (char) (i & 0xFF);
			line = line.append(c);
			i = is.read();
		}
		if (i == 13) { // 10 is unix LF, but DOS does 13+10, so read the 10 if we got 13
			i = is.read();
		}

		return line.toString();
	}

	public static Socket createSSLWrapper(Socket socket) throws IOException {
		String hostName = socket.getInetAddress().getHostName();
		int port = socket.getPort();
		SSLSocket sslSocketWrapper = (SSLSocket) sslSocketFactory.createSocket(socket, hostName, port, true);
		sslSocketWrapper.setUseClientMode(false);
		return sslSocketWrapper;
	}

	public static Socket createSSLSocket(String host, int port) throws UnknownHostException, IOException {
		return sslSocketFactory.createSocket(host, port);
	}

	public static Socket createSocket(String host, int port) throws UnknownHostException, IOException {
		try {
			return new Socket(host, port);
		} catch (ConnectException e) {
			logger.error("cannot connect to " + host + ":" + port, e);
			throw e;
		}
	}
}
